package cn.ljw_jhc.booksearch;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by info on 16/12/22.
 */
public class BookSearchFragment extends Fragment
        implements ThumbnailDownloader.OnThumbnailDownloaded{

    private static final String TAG = "BookSearchFragment";

    private RecyclerView bookRecyclerView;
    private List<BookItem> bItems =new ArrayList<>();
    private Handler mainHandler = new Handler();
    private ThumbnailDownloader thumbnailDownloader;
    private String SearchKey=null;
    public void changeKey(String s){
         SearchKey=s;
        updateItems();
    }

    public static BookSearchFragment newInstance(){
        return new BookSearchFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        setHasOptionsMenu(true);
        thumbnailDownloader = new ThumbnailDownloader();
        thumbnailDownloader.start();
        thumbnailDownloader.setListener(this);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_booksearch,container,false);
        final EditText editText = (EditText) v.findViewById(R.id.editText);
        Button btn_search = (Button) v.findViewById(R.id.button);
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String qstr=editText.getText().toString();
                if(qstr.equals("")){
                    Toast.makeText(null, "请输入搜索关键词！", Toast.LENGTH_SHORT).show();
                }else{
                    changeKey(qstr);
                }
            }
        });



        bookRecyclerView = (RecyclerView) v.findViewById(R.id.fragment_book_search_recycler_view);
        bookRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));

        return v;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        thumbnailDownloader.quit();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
        super.onCreateOptionsMenu(menu, menuInflater);
        menuInflater.inflate(R.menu.fragment_booksearch, menu);

        MenuItem searchItem = menu.findItem(R.id.menu_item_search);
        final SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                Log.d(TAG, "QueryTextSubmit: " + s);
                changeKey(s);
                updateItems();
                return true;
            }
            @Override
            public boolean onQueryTextChange(String s) {
                Log.d(TAG, "QueryTextChange: " + s);
                return false;
            }
        });
    }

    private void updateItems() {
        new FetchItemsTask().execute();
    }

    @Override
    public void onThumbnailDownloaded(final Bitmap image, final BookHolder holder) {
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                holder.bindImage(image);
            }
        });
    }



    private class FetchItemsTask extends AsyncTask<Void,Void,List<BookItem>>{

        @Override
        protected List<BookItem> doInBackground(Void... params) {
            return new DoubanFetcher().fetchItem(SearchKey);
        }

        @Override
        protected void onPostExecute(List<BookItem> items) {
            bItems =items;
            bookRecyclerView.setAdapter(new BookAdapter(items));
            bookRecyclerView.getAdapter().notifyDataSetChanged();
        }
    }

    class BookHolder extends RecyclerView.ViewHolder{
        private TextView titleView;
        private ImageView bookImg;
        private BookItem bookItems;

        public BookHolder(View itemView) {
            super(itemView);
            titleView = (TextView) itemView.findViewById(R.id.book_item_text_view);
            bookImg = (ImageView) itemView.findViewById(R.id.book_item_image_view);

        }

        public void bindBookItem(BookItem item){
            titleView.setText(item.getTitle());
            this.bookItems=item;
        }

        public void bindImage(Bitmap bitmap){
            bookImg.setImageBitmap(bitmap);
            bookImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(bookItems.getUrl()));
                    startActivity(intent);
                }
            });
        }
    }

    private class BookAdapter extends RecyclerView.Adapter<BookHolder>{
        private List<BookItem> bookItems;
        public BookAdapter(List<BookItem> items){
            bookItems=items;
        }

        @Override
        public BookHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            View view = inflater.inflate(R.layout.gallery_item,parent,false);
            return new BookHolder(view);
        }

        @Override
        public void onBindViewHolder(BookHolder holder, int position) {
            BookItem bookItem = bookItems.get(position);
            holder.bindBookItem(bookItem);

            thumbnailDownloader.queueDownloader(holder,bookItem.getImgURL());
        }

        @Override
        public int getItemCount() {
            return bookItems.size();
        }
    }
}
